package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理超时订单
     */
    //@Scheduled(cron = "0 * * * * ? ")
    //@Scheduled(cron = "1/5 * * * * ?")
    public void outOrderTime(){
        log.info("处理超时订单：{}", LocalDateTime.now());

        //首先查询订单表里面超过15分钟的订单并且订单状态是待接单。
            //获取当前时间并减去15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> list =  ordersMapper.getByStatusAndOrderTimeLt(Orders.PENDING_PAYMENT,time);

        if(!list.isEmpty()){

            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                ordersMapper.update(orders);
            }
        }
    }

    /**
     * 处理上一个工作日还处于派送中的订单
     */
    //@Scheduled(cron = "0 0 1 * * ? ")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单:{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> list = ordersMapper.getByStatusAndOrderTimeLt(Orders.DELIVERY_IN_PROGRESS, time);
        if(!list.isEmpty()){

            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders);
            }
        }
    }
}
